import { match, RoutingContext, createMemoryHistory } from 'dva/router';
import { renderToString } from 'react-dom/server'
import { routes } from '../isomorphism/router';
import createApp from '../isomorphism/createApp';
import config from './utils/config';
import createLoading from 'dva-loading';

export default function (req, res) {
  match({
    routes,
    location: req.url,
  }, (err, redirectLocation, renderProps) => {
    if (err) {
      res.status(500).end(`Internal Server Error ${err}`);
    }
    else if (redirectLocation) {
      res.redirect(302, redirectLocation.pathname + redirectLocation.search);
    } else if (renderProps) {
      const other = createApp({
        history: createMemoryHistory(),
      }, true);
      const otherhtml = renderToString(other.start()({ renderProps }));
      const loginuser = req.session.user || {};
      const loginstate = req.session.user ? true : false;
      res.end(renderFullPage(otherhtml, { staticServer: config.staticServer, sessionid: req.session.id, userinfo: loginuser, islogin: loginstate }));
    } else {
      res.status(404).send('Not found');
    }
  });
}

function renderFullPage(html, initialState) {
  //加载脚本
  let scriptLink = " <script src='" + config.staticServer + "/vendor.bundle.js' ></script>";
  scriptLink += "<script src='" + config.staticServer + "/index.bundle.js'></script>";

  //加载样式
  let cssLink = "<link rel=\"stylesheet\" href='" + config.staticServer + "/index.css?v=" + config.version + "' />"

  if (process.env.NODE_ENV !== 'production') {
    scriptLink = " <script src=\"/static/vendor.bundle.js\"></script>";
    scriptLink += "<script src=\"/static/index.bundle.js\"></script>";
    cssLink = '<link rel="stylesheet" href="/static/index.css?v=' + config.version + '" />';

  }
  return `
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="${config.staticServer}antd.min.css" />
 ${cssLink}
 
</head>
<body>
  <div id="root" class='root-box'>
    <div>
      ${html}
    </div>
  </div>
  <script>
    window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
  </script>
 ${scriptLink}
</body>
</html>
  `;
}
